<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="5">
        <el-button
          v-hasPermi="['system:role:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >
          新增活动
        </el-button>
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="activityList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" width="100" type="index" />
      <el-table-column label="活动名称" prop="title" width="180" />
      <el-table-column label="扫码有效" prop="isScanCode" width="160">
        <template slot-scope="scope">
          <!-- <div>{{ scope.row.isScanCode == 1 ? "扫码有效" : "其他" }}</div> -->
          <div>{{ scope.row.isScanCode == 1 ? "扫码有效" : "扫码有效" }}</div>
        </template>
      </el-table-column>
      <el-table-column label="活动地区" prop="provinceId" width="260">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.provinceId"
            placeholder="活动地区"
            clearable
            multiple
            disabled
          >
            <el-option
              v-for="dict in countryList"
              :key="dict.code"
              :label="dict.name"
              :value="dict.code"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="活动时间" prop="created" width="320" />
      <el-table-column label="活动规则" prop="rules" width="230">
        <template slot-scope="scope">
          <!-- <div>{{ scope.row.isScanCode == 1 ? "扫码有效" : "其他" }}</div> -->
          <div>
            {{
              scope.row.rules == 1
                ? "首次参与活动获得谢谢参与的用户"
                : "首次参与活动获得谢谢参与的用户"
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="库存" prop="inventory" width="220" />
      <el-table-column label="活动状态" prop="statusDesc" width="160" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="300"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-popconfirm
            confirm-button-text="确认"
            cancel-button-text="取消"
            icon-color="#626AEF"
            title="确定要暂停该激活红包规则吗？暂停后该激活红包规则将不再生效！"
            @confirm="confirmEvent(scope.row)"
            @cancel="cancelEvent"
          >
            <template #reference>
              <el-button
                v-if="scope.row.status == 0"
                size="mini"
                type="text"
                icon="el-icon-lock"
                @click="handlePause()"
              >
                取消
              </el-button>
            </template>
          </el-popconfirm>
          <el-button
            v-if="
              scope.row.statusDesc == '未开始' ||
              scope.row.statusDesc == '进行中'
            "
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="tableParams.pageNum"
      :limit.sync="tableParams.pageSize"
      @pagination="getList"
    />
    <!-- 新增弹出窗口 -->
    <el-dialog
      v-model="ruleshow"
      :title="title"
      width="1000px"
      append-to-body
      :visible.sync="open"
    >
      <el-form
        ref="queryAddForm"
        :model="purchaseAddForm"
        size="small"
        :inline="true"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="活动名称" prop="title">
              <el-input
                v-model="purchaseAddForm.title"
                placeholder="活动名称"
                clearable
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="扫码有效" prop="isScanCode">
              <template #default>
                <div>
                  {{ purchaseAddForm.isScanCode == 1 ? "扫码有效" : "其他" }}
                </div>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="关联商户号" prop="mchId">
              <el-input
                v-model="purchaseAddForm.mchId"
                placeholder="关联商户号"
                clearable
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="抽奖次数" prop="mchId">
              <div style="display: flex; align-items: center">
                <el-input
                  v-model="purchaseAddForm.min"
                  placeholder="最小次数"
                  clearable
                  min="1"
                  disabled
                />
                -
                <el-input
                  v-model="purchaseAddForm.max"
                  placeholder="最大次数"
                  clearable
                  min="1"
                  disabled
                />
                <p>且</p>
                <el-input
                  v-model="purchaseAddForm.text"
                  placeholder="条件"
                  clearable
                  disabled
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="活动地区" prop="provinceId">
              <template #default>
                <el-select
                  v-model="purchaseAddForm.provinceId"
                  placeholder="活动地区"
                  clearable
                  multiple
                >
                  <el-option
                    v-for="dict in countryList"
                    :key="dict.code"
                    :label="dict.name"
                    :value="dict.code"
                    :disabled="ruleEdit == false"
                  />
                </el-select>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动时间" prop="created">
              <el-date-picker
                v-model="purchaseAddForm.created"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                size="small"
                :disabled="ruleEdit == false"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 弹窗表格 -->
      <el-table :data="purchaseAddForm.rewardList" style="width: 100%">
        <el-table-column prop="id" label="奖品id" width="120">
        </el-table-column>
        <el-table-column prop="title" label="奖品名称" width="180">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.title"
              placeholder="名称"
              clearable
              disabled
            />
          </template>
        </el-table-column>
        <el-table-column prop="num" label="奖品金额" width="250">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.num"
              placeholder="奖品金额"
              clearable
              type="number"
              min="1"
              disabled
            />
          </template>
        </el-table-column>
        <el-table-column prop="effectiveTime" label="激活有效期(h)" width="250">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.effectiveTime"
              placeholder="激活有效期"
              clearable
              :disabled="ruleEdit == false"
            >
              <el-option
                v-for="dict in timeList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select> </template
        ></el-table-column>
        <el-table-column prop="max" label="库存" width="150">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.max"
              placeholder="库存"
              clearable
              type="number"
              min="1"
              :disabled="ruleEdit == false"
            />
          </template>
        </el-table-column>
      </el-table>
      <div class="dialog-footer" slot="footer">
        <el-button @click="cancelSetting">返回</el-button>
        <el-button
          type="primary"
          @click="confirmSetting"
          v-if="ruleEdit == true"
          >保存设置</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import china from "../../assets/json/china.json";
import {
  getActivityPacketReward,
  cancelActivityPacketReward,
  getActivityPacketRewardById,
  updateActivityPacketRewardById,
} from "@/api/activity/index";
export default {
  name: "RedPacket",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //   是否弹出层
      open: false,
      // 表格数据
      activityList: [],
      // 弹窗展示
      ruleshow: false,
      // 是否可编辑
      ruleEdit: false,
      ruleEditShow: false,
      // 新增弹窗表格
      purchaseAddForm: {},
      // 奖品列表
      rewardList: [],
      tableData: [],
      // 大奖表单
      rewardForm: [],
      //   标题
      title: "",
      // 表单查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        activetyName: "",
        isScan: "",
        address: "",
        time: "",
        reward: "",
        isLimit: "",
        status: "",
      },
      // 城市列表
      countryList: [],
      timeList: [
        {
          value: 24,
          label: "24h",
        },
        {
          value: 48,
          label: "48h",
        },
      ],
      // 表单校验
      rules: {},
      // 表格分页数据
      tableParams: {
        pageNum: 1,
        pageSize: 10,
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.countryList = china;
      getActivityPacketReward(this.tableParams).then((res) => {
        res.data.records.forEach((element) => {
          element.created =
            this.formatDate(new Date(element.startTime)) +
            "-" +
            this.formatDate(new Date(element.endTime));
          element.provinceId = element.provinceId.split(",");
        });
        this.activityList = res.data.records;
        this.loading = false;
        this.total = res.data.total;
      });
    },
    handleQuery() {},
    resetQuery() {},
    handleSelectionChange() {},
    handleAdd() {
      this.$router.push("/activity/add");
    },
    handleEdit(row) {
      console.log(row, "edi");
      this.open = true;
      this.ruleshow = true;
      this.title = "编辑激活红包规则";
      if (row.statusDesc == "未开始") {
        this.ruleEdit = true;
      } else {
        this.ruleEdit = false;
      }
      getActivityPacketRewardById(row.id).then((res) => {
        if (res.code == 0) {
          this.purchaseAddForm = {
            title: "叠加活动—激活红包",
            isScanCode: 1,
            mchId: "",
            min: 1,
            max: "1",
            text: "谢谢参与",
            rewardList: [
              {
                id: res.data.id,
                title: res.data.title,
                num: res.data.num,
                effectiveTime: res.data.effectiveTime,
                max: res.data.max,
              },
            ],
            created: [new Date(res.data.startTime), new Date(res.data.endTime)],
            provinceId: res.data.provinceId.split(","),
          };
        }
      });
      /**created: "2024-03-14T17:28:28"
effectiveTime: 24
endTime: 1735660799000
id: 1
max: 2380000
modified: "2024-03-17T11:18:06"
num: 168
provinceId: "11,12,13"
startTime: 1735660799000
status: 0
title: "1.68元红包" */
    },
    handlePause() {},
    confirmEvent(item) {
      let params = {
        id: item.id,
      };
      cancelActivityPacketReward(params).then((res) => {
        if (res.code == 0) {
          this.$message.success("取消成功");
          this.getList();
        }
      });
    },
    cancelEvent() {},
    handleOpen(id) {},
    confirmSetting() {
      if(!this.purchaseAddForm.created){
        this.$message.error('请选择活动时间')
        return;
      }
      let params = {
        id: this.purchaseAddForm.rewardList[0].id,
        title: this.purchaseAddForm.title,
        num: this.purchaseAddForm.rewardList[0].num,
        effectiveTime: this.purchaseAddForm.rewardList[0].effectiveTime,
        max: this.purchaseAddForm.rewardList[0].max,
        startTime: new Date(this.purchaseAddForm.created[0]).getTime(),
        endTime: new Date(this.purchaseAddForm.created[1]).getTime(),
        provinceId: this.purchaseAddForm.provinceId.join(","),
      };
      console.log(params,'updateActivityPacketRewardById');
      updateActivityPacketRewardById(params).then((res) => {
        if (res.code == 0) {
          this.$message.success("更新激活红包成功");
          this.ruleshow = false
          this.open = false
          this.purchaseEditForm = {
            title: "叠加活动—激活红包",
            isScanCode: 1,
            mchId: "",
            min: 1,
            max: "1",
            text: "谢谢参与",
            rewardList: [],

            provinceId: "",
          };
        }
      });
    },
    cancelSetting() {
      this.open = false;
    },
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear().toString();
      const month = ("0" + (date.getMonth() + 1)).slice(-2);
      const day = ("0" + date.getDate()).slice(-2);
      let hour = date.getHours();
      if (hour.toString().length < 2) {
        hour = "0" + hour;
      }
      let seconds = date.getSeconds();
      if (seconds.toString().length < 2) {
        seconds = "0" + seconds;
      }
      let minutes = date.getMinutes();
      if (minutes.toString().length < 2) {
        minutes = "0" + minutes;
      }
      return `${year}-${month}-${day} ${hour}:${minutes}:${seconds}`;
    },
  },
};
</script>

<style scoped lang="scss">
.frequency {
  .el-input {
    width: 100px;
  }
}
</style>
